from rest_framework import serializers
from .models import OAUser,ChoiceUserStatus,OADepartment
from rest_framework import exceptions

class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)
    password = serializers.CharField(max_length=20,min_length=6)

    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        if email and password:
            user = OAUser.objects.filter(email=email).first()
            if not user:
                raise serializers.ValidationError('请输入正确的邮箱')
            if not user.check_password(password):
                raise serializers.ValidationError('密码输入错误')
            if user.status == ChoiceUserStatus.UNACTIVE:
                raise serializers.ValidationError('该用户未激活')
            elif user.status == ChoiceUserStatus.LOCK:
                raise serializers.ValidationError('该用户被锁定，请联系管理员')
            # 为了节省执行sql语句的次数 这里我们把user直接放到attrs中 方便在视图中使用
            attrs['user'] = user
        else:
            raise serializers.ValidationError('请输入邮箱和密码')
        return attrs

class DepartmentSerialize(serializers.ModelSerializer):
    class Meta:
        model = OADepartment
        fields = '__all__'
class UserSerializer(serializers.ModelSerializer):
    department = DepartmentSerialize()
    class Meta:
        model = OAUser
        # fields = '__all__'
        exclude = ['password','groups','user_permissions']

class ResetPwdSerializer(serializers.Serializer):
    oldpwd = serializers.CharField(min_length=6,max_length=20)
    pwd1 = serializers.CharField(min_length=6,max_length=20)
    pwd2 = serializers.CharField(min_length=6,max_length=20)

    def validate(self, attrs):
        oldpwd = attrs['oldpwd']
        pwd1 = attrs['pwd1']
        pwd2 = attrs['pwd2']

        # 这里我们要获取到之前
        user = self.context['request'].user
        if not user.check_password(oldpwd):
            raise exceptions.ValidationError('旧密码不正确！')
        if pwd1 != pwd2:
            raise exceptions.ValidationError('两次密码不一致！')
        return attrs